package com.lineage.william;

import com.lineage.DatabaseFactory;
import com.lineage.server.datatables.ItemTable;
import com.lineage.server.datatables.lock.CharItemsReading;
import com.lineage.server.model.Instance.L1ItemInstance;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.serverpackets.S_AddItem;
import com.lineage.server.serverpackets.S_DeleteInventoryItem;
import com.lineage.server.serverpackets.S_ServerMessage;
import com.lineage.server.serverpackets.S_SkillSound;
import com.lineage.server.serverpackets.S_SystemMessage;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.templates.L1Item;
import com.lineage.server.utils.PerformanceTimer;
import com.lineage.server.utils.RandomArrayList;
import com.lineage.server.utils.log.PlayerLogUtil;
import com.lineage.server.world.World;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.StringTokenizer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ItemIntegration {
  private static final Log _logx = LogFactory.getLog(ItemIntegration.class);
  
  private static ArrayList<ArrayList<Object>> aData20 = new ArrayList<>();
  
  public static final String TOKEN = ",";
  
  private static ItemIntegration _instance;
  
  public static ItemIntegration getInstance() {
    if (_instance == null)
      _instance = new ItemIntegration(); 
    return _instance;
  }
  
  public static void reload() {
    aData20.clear();
    _instance = null;
    getInstance();
  }
  
  public static void forItemIntegration(L1PcInstance pc, L1ItemInstance item, L1ItemInstance itemG) {
    int itemid = item.getItem().getItemId();
    ArrayList<?> aTempData = null;
    int i = 0;
    while (i < aData20.size()) {
      aTempData = aData20.get(i);
      if (((Integer)aTempData.get(0)).intValue() == itemid && 
        itemG.getItem().getItemId() == ((Integer)aTempData.get(4)).intValue()) {
        if (pc.getInventory().getSize() >= 170) {
          pc.sendPackets((ServerBasePacket)new S_ServerMessage("身上物品太多,无法操作"));
          return;
        } 
        if (pc.getInventory().getWeight() / pc.getMaxWeight() * 100.0D > 90.0D) {
          pc.sendPackets((ServerBasePacket)new S_ServerMessage("身上物品负重,无法操作"));
          return;
        } 
        if (!itemG.getItem().isgivebless()) {
          pc.sendPackets((ServerBasePacket)new S_SystemMessage("该物品无法进行祝福。"));
          return;
        } 
        if (((Integer)aTempData.get(1)).intValue() != 0) {
          byte class_id = 0;
          String msg = "";
          if (pc.isCrown()) {
            class_id = 1;
          } else if (pc.isKnight()) {
            class_id = 2;
          } else if (pc.isWizard()) {
            class_id = 3;
          } else if (pc.isElf()) {
            class_id = 4;
          } else if (pc.isDarkelf()) {
            class_id = 5;
          } 
          switch (((Integer)aTempData.get(1)).intValue()) {
            case 1:
              msg = "王族";
              break;
            case 2:
              msg = "骑士";
              break;
            case 3:
              msg = "法师";
              break;
            case 4:
              msg = "妖精";
              break;
            case 5:
              msg = "黑暗妖精";
              break;
          } 
          if (((Integer)aTempData.get(1)).intValue() != class_id && !pc.isGm()) {
            pc.sendPackets((ServerBasePacket)new S_SystemMessage("你的职业无法使用" + msg + "的专属道具。"));
            return;
          } 
        } 
        if (((Integer)aTempData.get(2)).intValue() != 0 && !pc.isGm() && 
          pc.getLevel() < ((Integer)aTempData.get(2)).intValue()) {
          pc.sendPackets((ServerBasePacket)new S_SystemMessage("等级" + ((Integer)aTempData.get(2)).intValue() + "以上才可使用此道具。"));
          return;
        } 
        if (item.getCount() < ((Integer)aTempData.get(3)).intValue() && (
          (Integer)aTempData.get(3)).intValue() != 0) {
          L1Item temp1 = ItemTable.get().getTemplate(itemid);
          pc.sendPackets((ServerBasePacket)new S_ServerMessage(337, 
                String.valueOf(String.valueOf(temp1.getName())) + "(" + (((Integer)aTempData.get(3)).intValue() - 
                pc.getInventory().countItems(temp1.getItemId())) + ")"));
          break;
        } 
        if (itemG.getItem().getItemId() != ((Integer)aTempData.get(4)).intValue()) {
          pc.sendPackets((ServerBasePacket)new S_ServerMessage("没发生什么事情"));
          break;
        } 
        if (itemG.getCount() < ((Integer)aTempData.get(5)).intValue()) {
          L1Item temp2 = ItemTable.get().getTemplate(((Integer)aTempData.get(4)).intValue());
          pc.sendPackets((ServerBasePacket)new S_ServerMessage(337, 
                String.valueOf(String.valueOf(temp2.getName())) + "(" + (((Integer)aTempData.get(5)).intValue() - 
                pc.getInventory().countItems(temp2.getItemId())) + ")"));
          break;
        } 
        if (itemG.getEnchantLevel() < ((Integer)aTempData.get(19)).intValue()) {
          pc.sendPackets((ServerBasePacket)new S_SystemMessage("该物品强化值需求+" + ((Integer)aTempData.get(19)).intValue()));
          break;
        } 
        if (((int[])aTempData.get(7) == null || (int[])aTempData.get(8) == null) && (
          (int[])aTempData.get(7) != null || (int[])aTempData.get(8) != null))
          break; 
        int[] materials = (int[])aTempData.get(7);
        int[] counts = (int[])aTempData.get(8);
        boolean isCreate = true;
        if ((int[])aTempData.get(7) != null && (int[])aTempData.get(8) != null) {
          int j = 0;
          while (j < materials.length) {
            if (!pc.getInventory().checkItem(materials[j], counts[j])) {
              L1Item temp3 = ItemTable.get().getTemplate(materials[j]);
              pc.sendPackets((ServerBasePacket)new S_ServerMessage(337, String.valueOf(String.valueOf(temp3.getName())) + "(" + (
                    counts[j] - pc.getInventory().countItems(temp3.getItemId())) + ")"));
              isCreate = false;
            } 
            j++;
          } 
        } 
        if (!isCreate)
          break; 
        if ((int[])aTempData.get(7) != null && (int[])aTempData.get(8) != null) {
          int k = 0;
          while (k < materials.length) {
            pc.getInventory().consumeItem(materials[k], counts[k]);
            k++;
          } 
        } 
        if (((Integer)aTempData.get(3)).intValue() != 0)
          pc.getInventory().removeItem(item, ((Integer)aTempData.get(3)).intValue()); 
        if ((int[])aTempData.get(9) == null || (int[])aTempData.get(10) == null)
          break; 
        int[] giveMaterials = (int[])aTempData.get(9);
        int[] giveCounts = (int[])aTempData.get(10);
        int rnd = ((Integer)aTempData.get(6)).intValue();
        if (RandomArrayList.getInc(100, 1) <= rnd) {
          int l = 0;
          while (l < giveMaterials.length) {
            L1ItemInstance item2 = ItemTable.get().createItem(giveMaterials[l]);
            if (item2.isStackable()) {
              item2.setCount(giveCounts[l]);
            } else {
              item2.setCount(1L);
            } 
            if (item2 != null) {
              if (itemG.getItem().getType2() == 0 && item2.getItem().getType2() == 0) {
                if (itemG.getItem().getType() == 32) {
                  强化道具(pc, itemG, giveMaterials[l]);
                } else {
                  pc.getInventory().removeItem(itemG, ((Integer)aTempData.get(5)).intValue());
                  if (pc.getInventory().checkAddItem(item2, giveCounts[l]) == 0) {
                    pc.getInventory().storeItem(item2);
                  } else {
                    World.get().getInventory(pc.getX(), pc.getY(), pc.getMapId()).storeItem(item2);
                  } 
                } 
              } else if (itemG.getItem().getType2() == 1 && item2.getItem().getType2() == 1) {
                强化武器(pc, itemG, giveMaterials[l], ((Integer)aTempData.get(16)).intValue());
              } else if (itemG.getItem().getType2() == 2 && item2.getItem().getType2() == 2) {
                强化装备(pc, itemG, giveMaterials[l], ((Integer)aTempData.get(16)).intValue());
              } 
              if ((String)aTempData.get(11) != null) {
                pc.sendPackets((ServerBasePacket)new S_SystemMessage((String)aTempData.get(11)));
              } else {
                pc.sendPackets((ServerBasePacket)new S_ServerMessage(403, item2.getLogName()));
              } 
              if ((String)aTempData.get(18) != null)
                World.get()
                  .broadcastPacketToAll((ServerBasePacket)new S_SystemMessage(
                      String.format((String)aTempData.get(18), new Object[] { pc.getName(), 
                          "+" + itemG.getEnchantLevel() + item2.getViewName() }))); 
              if (((Integer)aTempData.get(12)).intValue() != 0) {
                pc.sendPackets((ServerBasePacket)new S_SkillSound(pc.getId(), ((Integer)aTempData.get(12)).intValue()));
                pc.broadcastPacketAll(
                    (ServerBasePacket)new S_SkillSound(pc.getId(), ((Integer)aTempData.get(12)).intValue()));
              } 
              祝福升级成功("玩家 :" + pc.getName() + " 使用(" + item.getName() + ") 对 (+" + itemG.getEnchantLevel() + 
                  item2.getViewName() + ")升级成功 ,时间:" + new Timestamp(System.currentTimeMillis()) + 
                  ")");
            } 
            l++;
          } 
          break;
        } 
        if (((Integer)aTempData.get(13)).intValue() != 0)
          pc.getInventory().removeItem(itemG, ((Integer)aTempData.get(5)).intValue()); 
        if ((String)aTempData.get(14) != null)
          pc.sendPackets((ServerBasePacket)new S_SystemMessage((String)aTempData.get(14))); 
        祝福升级失败("玩家 :" + pc.getName() + " 使用(" + item.getName() + ") 对 (+" + itemG.getViewName() + ")升级(失败) ,时间:" + 
            new Timestamp(System.currentTimeMillis()) + ")");
        if (((Integer)aTempData.get(15)).intValue() == 0)
          pc.getInventory().removeItem(itemG, 1L); 
        break;
      } 
      i++;
    } 
  }
  
  public static void 祝福升级成功(String info) {
    PlayerLogUtil.writeLog("[祝福升级成功]", info);
  }
  
  public static void 祝福升级失败(String info) {
    PlayerLogUtil.writeLog("[祝福升级失败]", info);
  }
  
  private ItemIntegration() {
    PerformanceTimer timer = new PerformanceTimer();
    Connection con = null;
    try {
      con = DatabaseFactory.get().getConnection();
      Statement stat = con.createStatement();
      ResultSet rset = stat.executeQuery("SELECT * FROM w_道具升级");
      ArrayList<Object> aReturn = null;
      if (rset != null)
        while (rset.next()) {
          aReturn = new ArrayList();
          aReturn.add(0, new Integer(rset.getInt("item_id")));
          aReturn.add(1, new Integer(rset.getInt("checkClass")));
          aReturn.add(2, new Integer(rset.getInt("level")));
          aReturn.add(3, new Integer(rset.getInt("needCount")));
          aReturn.add(4, new Integer(rset.getInt("Integration_ID")));
          aReturn.add(5, new Integer(rset.getInt("Integration_count")));
          aReturn.add(6, new Integer(rset.getInt("random")));
          if (rset.getString("materials") != null && !rset.getString("materials").equals("") && 
            !rset.getString("materials").equals("0")) {
            aReturn.add(7, getArray(rset.getString("materials"), ",", 1));
          } else {
            aReturn.add(7, null);
          } 
          if (rset.getString("counts") != null && !rset.getString("counts").equals("") && 
            !rset.getString("counts").equals("0")) {
            aReturn.add(8, getArray(rset.getString("counts"), ",", 1));
          } else {
            aReturn.add(8, null);
          } 
          if (rset.getString("new_item") != null && !rset.getString("new_item").equals("") && 
            !rset.getString("new_item").equals("0")) {
            aReturn.add(9, getArray(rset.getString("new_item"), ",", 1));
          } else {
            aReturn.add(9, null);
          } 
          if (rset.getString("new_item_counts") != null && !rset.getString("new_item_counts").equals("") && 
            !rset.getString("new_item_counts").equals("0")) {
            aReturn.add(10, getArray(rset.getString("new_item_counts"), ",", 1));
          } else {
            aReturn.add(10, null);
          } 
          aReturn.add(11, rset.getString("msg"));
          aReturn.add(12, new Integer(rset.getInt("gfxId")));
          aReturn.add(13, new Integer(rset.getInt("Failure_down")));
          aReturn.add(14, rset.getString("Failure_msg"));
          aReturn.add(15, new Integer(rset.getInt("Failure_keep")));
          aReturn.add(16, new Integer(rset.getInt("keep")));
          aReturn.add(17, new Integer(rset.getInt("keep_materials")));
          aReturn.add(18, rset.getString("All_message"));
          aReturn.add(19, new Integer(rset.getInt("EnchantItem")));
          aData20.add(aReturn);
        }  
      stat.close();
      rset.close();
      if (con != null && !con.isClosed())
        con.close(); 
    } catch (Exception exception) {}
  }
  
  private static Object getArray(String s, String sToken, int iType) {
    StringTokenizer st = new StringTokenizer(s, sToken);
    int iSize = st.countTokens();
    String sTemp = null;
    if (iType == 1) {
      int[] iReturn = new int[iSize];
      int i = 0;
      while (i < iSize) {
        sTemp = st.nextToken();
        iReturn[i] = Integer.parseInt(sTemp);
        i++;
      } 
      return iReturn;
    } 
    if (iType == 2) {
      String[] sReturn = new String[iSize];
      int i = 0;
      while (i < iSize) {
        sTemp = st.nextToken();
        sReturn[i] = sTemp;
        i++;
      } 
      return sReturn;
    } 
    if (iType == 3) {
      String sReturn2 = null;
      int i = 0;
      while (i < iSize) {
        sTemp = sReturn2 = st.nextToken();
        i++;
      } 
      return sReturn2;
    } 
    return null;
  }
  
  private static void 强化装备(L1PcInstance pc, L1ItemInstance item, int new_ItemId, int keep) {
    L1Item l1item = ItemTable.get().getTemplate(new_ItemId);
    pc.sendPackets((ServerBasePacket)new S_DeleteInventoryItem(item.getId()));
    item.setItemId(new_ItemId);
    item.setItem(l1item);
    item.setBless(l1item.getBless());
    try {
      CharItemsReading.get().updateItemId_Name(item);
    } catch (Exception e) {
      e.printStackTrace();
    } 
    pc.sendPackets((ServerBasePacket)new S_AddItem(item));
    pc.sendPackets((ServerBasePacket)new S_ServerMessage(403, item.getLogName()));
  }
  
  private static void 强化武器(L1PcInstance pc, L1ItemInstance item, int new_ItemId, int keep) {
    L1Item l1item = ItemTable.get().getTemplate(new_ItemId);
    pc.sendPackets((ServerBasePacket)new S_DeleteInventoryItem(item.getId()));
    item.setItemId(new_ItemId);
    item.setItem(l1item);
    item.setBless(l1item.getBless());
    try {
      CharItemsReading.get().updateItemId_Name(item);
    } catch (Exception e) {
      e.printStackTrace();
    } 
    pc.sendPackets((ServerBasePacket)new S_AddItem(item));
    pc.sendPackets((ServerBasePacket)new S_ServerMessage(403, item.getLogName()));
  }
  
  private static void 强化道具(L1PcInstance pc, L1ItemInstance item, int new_ItemId) {
    L1Item l1item = ItemTable.get().getTemplate(new_ItemId);
    pc.sendPackets((ServerBasePacket)new S_DeleteInventoryItem(item.getId()));
    item.setItemId(new_ItemId);
    item.setItem(l1item);
    item.setBless(l1item.getBless());
    try {
      CharItemsReading.get().updateItemId_Name(item);
    } catch (Exception e) {
      e.printStackTrace();
    } 
    pc.sendPackets((ServerBasePacket)new S_AddItem(item));
    pc.sendPackets((ServerBasePacket)new S_ServerMessage(403, item.getLogName()));
  }
}
